package com.wikso.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.LinkedList;
import java.util.List;

public class DBUtil extends DBOperation {

	public static void exec(Connection conn, SqlBean<?> sql, Object... args)
			throws Exception {
		PreparedStatement stmt = null;
		try {
			stmt = getSqlst(conn, sql, args);
			stmt.execute();
		} finally {
			close(stmt, null);
		}
	}

	// TODO
	public static int getExecResult(Connection conn, SqlBean<?> sql,
			Object... args) throws Exception {
		PreparedStatement stmt = null;
		try {
			stmt = getSqlst(conn, sql, args);
			stmt.execute();
		} finally {
			close(stmt, null);
		}
		return 0;
	}

	public static <E> E getObject(Connection conn, SqlBean<E> sql,
			Object... args) throws Exception {
		E ele = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			stmt = getSqlst(conn, sql, args);
			rs = stmt.executeQuery();
			ResultSetMetaData md = rs.getMetaData();
			int w = md.getColumnCount();
			if (rs.next()) {
				ele = getEle(sql, w, md, rs);
			}
			if (rs.next()) {
				throw new Exception("many rseult,not one!");
			}
		} finally {
			DBUtil.close(stmt, rs);
		}
		return ele;
	}

	public static <E> List<E> getList(Connection conn, SqlBean<E> sql,
			Object... args) throws Exception {
		final LinkedList<E> list = new LinkedList<E>();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			stmt = getSqlst(conn, sql, args);
			rs = stmt.executeQuery();
			ResultSetMetaData md = rs.getMetaData();
			int w = md.getColumnCount();
			while (rs.next()) {
				list.add(getEle(sql, w, md, rs));
			}
		} finally {
			close(stmt, rs);
		}
		return list;
	}

	public static void save(Connection conn, Object obj) {

	}

	public static void update(Connection conn, Object obj) {

	}

	/*
	 * protected String cols, tblName, id; protected boolean findpk = false;
	 * public boolean autopk = true;
	 * 
	 * @Override public Object getResult(Connection conn, Object[] args) {
	 * PreparedStatement stmt = null; try { Object obj = args[0]; Method[] ms =
	 * obj.getClass().getMethods(); StringBuffer sb = new
	 * StringBuffer("insert into "); StringBuffer sb2 = new StringBuffer();
	 * 
	 * sb.append(tblName);
	 * 
	 * ArrayList<Object> valList = new ArrayList<Object>(); sb.append("("); for
	 * (Method m : ms) { String n = m.getName(); if (!n.equals("getClass") &&
	 * m.getParameterTypes().length == 0 && n.startsWith("get")) { Object val =
	 * m.invoke(obj, NullObject); if (val != null) { n = n.substring(3); if
	 * (cols.indexOf(',' + n.toLowerCase() + ',') >= 0) { if (this.autopk &&
	 * id!=null && id.equalsIgnoreCase(n)) { continue; }
	 * sb.append(Character.toLowerCase(n.charAt(0)));
	 * sb.append(n.substring(1)).append(","); sb2.append("?,");
	 * valList.add(m.invoke(obj, NullObject)); } } } } sb.delete(sb.length() -
	 * 1, sb.length()); sb2.delete(sb2.length() - 1, sb2.length());
	 * sb.append(")values(").append(sb2).append(")"); LOG.info("sql:" +
	 * sb.toString()); // if (pk != null && findpk && dbtype != sqlite) { //
	 * PreparedStatement stmt = null; // try { // stmt =
	 * conn.prepareStatement(sb.toString(), // Statement.RETURN_GENERATED_KEYS);
	 * // stsql(stmt, sb.toString(), list.toArray()); // stmt.execute(); //
	 * String set = "set" + autopk; // for (Method m : ms) { // if
	 * (m.getName().equalsIgnoreCase(set) // && m.getParameterTypes().length ==
	 * 1) { // Class<?> cls = m.getParameterTypes()[0]; // char c =
	 * Character.toLowerCase(cls // .getSimpleName().toLowerCase() //
	 * .charAt(0)); // ResultSet rs = stmt.getGeneratedKeys(); // if (rs.next())
	 * { // if (c == 'i') { // m.invoke(obj, rs.getInt(1)); // } else if (c ==
	 * 'l') { // m.invoke(obj, rs.getLong(1)); // }
	 * 
	 * stmt = conn.prepareStatement(sb.toString()); for (int i = 0; i <
	 * valList.size(); i++) { stmt.setObject(i + 1, valList.get(i)); }
	 * stmt.execute();
	 * 
	 * } catch (Exception e) { e.printStackTrace(); } finally {
	 * DBUtil.close(stmt, null); }
	 * 
	 * return null; }
	 * 
	 * @Override public void anysql(Sql asql, Connection conn) throws Exception
	 * { Table tbl = target.getParameterTypes()[0].getAnnotation(Table.class);
	 * if (tbl != null) { tblName = tbl.name(); } else { tblName =
	 * target.getParameterTypes()[0].getSimpleName(); }
	 * LOG.info("save info tblName:" + tblName); cols =
	 * DBUtil.getColoumnsAsString(tblName, conn); LOG.info("save info  cols:" +
	 * cols); if (autopk) { Field[] fs =
	 * target.getParameterTypes()[0].getFields(); for (Field f : fs) { if
	 * (f.getAnnotation(Id.class) != null) { id = f.getName(); break; } } } }
	 */
}
